package com.wswy.wzcx.ui.activity;


import android.content.Intent;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdNative.SplashAdListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.bytedance.sdk.openadsdk.TTSplashAd.AdInteractionListener;
import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.utils.optional.Optional;
import com.check.ox.sdk.LionShListener;
import com.check.ox.sdk.LionShView;
import com.qq.e.ads.splash.SplashAD;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.api.Configs;
import com.wswy.wzcx.model.AdConfigs;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.module.AllAdConfLoader;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.ad.AdConfigLoader;
import com.wswy.wzcx.module.ad.TTAdManagerHolder;
import com.wswy.wzcx.statistics.BizReport;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.utils.FrescoUtils;

import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.subscribers.ResourceSubscriber;

import java.util.concurrent.TimeUnit;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import timber.log.Timber;

class SplashPresenter {

    private ISplashView mView;

    private boolean isTTAD = false;

    //是否请求过了穿山甲
    private boolean reqTTAD = false;
    //确认显示穿山甲广告
    private boolean nextTTAD = false;
    //确认显示异步方法
    private Runnable runnableTTAD = null;

    private ResourceSubscriber<Long> myAdDisposable;

    private long stTime = SystemClock.elapsedRealtime();

    private LionShView tuiaAdView;


    public SplashAD splashAD;

    SplashPresenter(ISplashView view) {
        this.mView = view;
    }


    void onCreate(Intent intent) {
        stTime = SystemClock.elapsedRealtime();
        GlobalConfigManager.getInstance().loadConfig();
    }

    void onDestroy() {
        cancelTrack();
        if (tuiaAdView != null) {
            tuiaAdView.destroy();
        }
    }


    //广点通开屏广告
    private void requestGDTAd() {
        isTTAD = false;
        View[] views = mView.getViews();
//        new SplashAD(mView.getActivity(), ((ViewGroup) views[0]), views[1],
//                AdConfigLoader.getGdtConfig().getAppId(),
//                AdConfigLoader.getGdtConfig().getSplashId(),
//                mView, 0);

//        new SplashAD(mView.getActivity(),((ViewGroup) views[0]),AdConfigLoader.getGdtConfig().getSplashId(),mView,0);
        splashAD= new SplashAD(mView.getActivity(),
                AdConfigLoader.getGdtConfig().getSplashId(), mView, 0);
        splashAD.fetchAdOnly();
//        splashAD.showAd(((ViewGroup) views[0]));
        splashAD.preLoad();
        splashAD.fetchAndShowIn(((ViewGroup) views[0]));
    }

    public void requestNoAd() {
        cancelTrack();
        long offset = (SystemClock.elapsedRealtime() - stTime);
        long max = 1500;
        mView.showNoAd();
        if (offset > max) {
            //大于3秒，直接启动
            mView.toNext();
        } else {
            //
            mView.toNext(max - offset);
        }

    }

    //头条开屏广告
    private void requestTTAD() {
        isTTAD = true;
        if (reqTTAD) {
            return;
        }
        Timber.e("requestTTAD --> ");
        reqTTAD = true;
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfigLoader.getCsjConfig().getSplashId())
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .build();

        TTAdNative ttAdNative = TTAdManagerHolder.getInstance(AppContext.getContext())
                .createAdNative(mView.getActivity());

        ttAdNative.loadSplashAd(adSlot, new SplashAdListener() {
            @Override
            public void onError(int i, String s) {
                Timber.e("requestTTAD error " + s + "   " + nextTTAD);
                BizReport.sendException(BizReport.TTAD_LOAD_ERROR, i + " " + s);
                reqTTAD = false;
                if (nextTTAD) {
                    requestGDTAd();
                } else {
                    runnableTTAD = new Runnable() {
                        @Override
                        public void run() {
                            //trackSkip();
                            //失败
                            requestGDTAd();
                        }
                    };

                }

            }

            @Override
            public void onTimeout() {
                Timber.e("requestTTAD onTimeout   " + nextTTAD);
                reqTTAD = false;
                if (nextTTAD) {
                    requestGDTAd();
                } else {
                    runnableTTAD = new Runnable() {
                        @Override
                        public void run() {
                            //trackSkip();

                            requestGDTAd();

                        }
                    };
                }

            }

            @Override
            public void onSplashAdLoad(final TTSplashAd ad) {
                Timber.e("requestTTAD onSplashAdLoad   " + nextTTAD);
                reqTTAD = false;
                if (ad == null) {
                    //如果广告加载失败
                    if (nextTTAD) {
                        requestNoAd();
                    }
                    return;
                }
                if (nextTTAD) {
                    handleTTAD(ad);
                } else {
                    runnableTTAD = new Runnable() {
                        @Override
                        public void run() {
                            handleTTAD(ad);
                        }
                    };
                }


            }
        }, 5000);

    }


    private void handleTTAD(TTSplashAd ad) {

        ad.setNotAllowSdkCountdown();
        //mView.getViews()[1].setVisibility(View.GONE);
        //mView.getViews()[2].setVisibility(View.GONE);
        View[] views = mView.getViews();
        ViewGroup container = (ViewGroup) views[0];

        views[2].setVisibility(View.VISIBLE);
        views[3].setVisibility(View.VISIBLE);

        container.setVisibility(View.VISIBLE);
        container.setBackgroundColor(Color.WHITE);

        LayoutParams layoutParams = container.getLayoutParams();
        if (layoutParams instanceof RelativeLayout.LayoutParams) {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) layoutParams;

            lp.addRule(RelativeLayout.ABOVE, 0);
            container.setLayoutParams(lp);
        }

        View view = ad.getSplashView();

        container.addView(view);
        mView.onShowAd();
        mView.displaySplash(null);
        trackSkip();


        ad.setSplashInteractionListener(new AdInteractionListener() {
            @Override
            public void onAdClicked(View view, int i) {
                StatTools.sendClick(AppContext.getContext(), StatisticsId.ad_splash_csj_click);
                Timber.e("onAdClicked --> 开屏广告点击 ");
            }

            @Override
            public void onAdShow(View view, int i) {
                Timber.e("onAdShow --> 开屏广告展示");
                StatTools.sendClick(AppContext.getContext(), StatisticsId.ad_splash_csj_show);
            }

            @Override
            public void onAdSkip() {
                mView.toNext();
            }

            @Override
            public void onAdTimeOver() {
                mView.toNext();

                Timber.e("onAdTimeOver --> 开屏广告倒计时结束");
            }
        });

    }


    private void requestTuiaAd() {

        tuiaAdView = new LionShView(mView.getActivity());

        tuiaAdView.setTargetClass(mView.getActivity(), GlobalConfigManager.getInstance().getFlavorConfigure().getMainActClass(), mView.toMainIntent());
        tuiaAdView.setCountTtime(5);
        tuiaAdView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        tuiaAdView.setAdListener(new LionShListener() {
            @Override
            public void onTimeOut() {
                Timber.e("onTimeOut --> ");
            }

            @Override
            public void onReceiveAd() {
                Timber.e("onReceiveAd --> ");
            }

            @Override
            public void onFailedToReceiveAd() {
                Timber.e("onFailedToReceiveAd --> ");
            }

            @Override
            public void onLoadFailed() {
                Timber.e("onLoadFailed --> ");
            }

            @Override
            public void onCloseClick() {
                Timber.e("onCloseClick --> ");
            }

            @Override
            public void onAdClick() {
                Timber.e("onAdClick --> ");

            }

            @Override
            public void onAdExposure() {
                Timber.e("onAdExposure --> ");

                trackSkip();
            }
        });
        tuiaAdView.loadAd(Configs.TUIA_SPLASH_AD);


        View[] views = mView.getViews();
        ViewGroup container = (ViewGroup) views[0];

        LayoutParams layoutParams = container.getLayoutParams();
        if (layoutParams instanceof RelativeLayout.LayoutParams) {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) layoutParams;

            lp.addRule(RelativeLayout.ABOVE, 0);
            container.setLayoutParams(lp);
        }

        container.addView(tuiaAdView);
        mView.displaySplash(null);


    }


    void requestAD() {
        loader();
        //requestTuiaAd();
    }


    private void loader() {
        requestTTAD();
        new AllAdConfLoader(AppContext.getContext()).loadOnce(
                new Function1<Optional<? extends AdConfigs>, Unit>() {
                    @Override
                    public Unit invoke(Optional<? extends AdConfigs> optional) {

                        AdConfigs configs = optional.orNull();
                        AdModel adModel = null;

                        GlobalConfigManager.getInstance().updateAdConfig(configs);

                        if (configs != null) {
                            adModel = configs.getSplashAdModel();
                        }

                        Timber.e("invoke -->splash  " + adModel);
                        loadOwnerSplash(adModel);

                        return null;
                    }
                });
    }

    //请求我们自己的
    private void loadOwnerSplash(AdModel adModel) {

        Single.just(Optional.ofNullable(adModel))
                .map(new Function<Optional<AdModel>, Optional<AdModel>>() {
                    @Override
                    public Optional<AdModel> apply(Optional<AdModel> splashAdModelOptional)
                            throws Exception {

                        AdModel splashAdModel = splashAdModelOptional.orNull();
                        if (splashAdModel != null && !TextUtils.isEmpty(splashAdModel.imgUrl)) {
                            FrescoUtils.downloadImage(splashAdModel.imgUrl);
                        }
                        return splashAdModelOptional;
                    }
                })
                .timeout(3, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new ApiOptionalResultObserver<AdModel>() {

            @Override
            protected void onApiResult(@Nullable AdModel splashAdModel) {
                if (splashAdModel != null) {
                    if (splashAdModel.showSelfAd()) {
                        mView.displaySplash(splashAdModel);
                        trackSkip();
                    } else {
                        if (splashAdModel.type != null) {
                            switch (splashAdModel.type) {
                                case AdModel.GDT: //广点通
                                    requestGDTAd();
                                    break;
                                case AdModel.TTAD: //头条
                                    if (runnableTTAD != null) {
                                        runnableTTAD.run();
                                    } else {
                                        nextTTAD = true;
                                        requestTTAD();
                                    }

                                    break;
                                default:
                                    requestNoAd();
                                    break;
                            }
                        } else {
                            requestNoAd();
                            //requestGDTAd();
                        }


                    }

                } else {
                    //没有广告
                    requestNoAd();

                }

            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                if (runnableTTAD != null) {
                    runnableTTAD.run();
                } else {
                    nextTTAD = true;
                    requestTTAD();
                }
            }
        });

    }


    private void trackSkip() {
        myAdDisposable = new ResourceSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {

                mView.onRemainTime(5 - aLong.intValue());
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {

            }
        };
        Flowable.intervalRange(0, 6, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(myAdDisposable);


    }

    void cancelTrack() {
        if (myAdDisposable != null) {
            myAdDisposable.dispose();
        }
        if (runnableTTAD != null) {
            runnableTTAD = null;
        }
    }

    boolean isTTAD() {
        return isTTAD;
    }

    public SplashAD getGDT(){
        return splashAD;

    }


}
